<?php
/* This file is part of Mirasol CMS
   (C) 2011-2012 by Chris Alban Hansen.
   Released under the terms of the GNU General Public License.
   See COPYING in the top level directory of the Mirasol CMS installation. */

include "{$_SERVER['DOCUMENT_ROOT']}/includes/config.php";
include "{$_SERVER['DOCUMENT_ROOT']}/includes/largetext.php";
include "{$_SERVER['DOCUMENT_ROOT']}/includes/settings.php";
include "{$_SERVER['DOCUMENT_ROOT']}/includes/xmlfeed.php";

if ($loadsubpage == 1)
{
  $pid = 0;
  $guid = isset ($_GET['guid']) ? $_GET['guid'] : "";
  $version = isset ($_GET['ver']) ? $_GET['ver'] : 0;
  $lastedit = 0;
  
  /* Get site name */
  $sitename = htmlentities (getsetting ($connection, "sitename"), ENT_COMPAT, "UTF-8", false);
  $domainname = htmlentities (getsetting ($connection, "domainname"), ENT_COMPAT, "UTF-8", false);
  $protocol = getsetting ($connection, "protocol");
  
  /* Get the relevant pid, version numbers and last edit */
  if (!empty ($guid))
    {
      /* Get pid of a specific version? */
      if (!empty ($version))
        {
          $result = mysql_query ("SELECT id, lastedit FROM ".db_maketablename ($table_pages_review)." WHERE guid LIKE '$guid' AND version='$version'");
          if (mysql_num_rows ($result) > 0)
            {
              $row = mysql_fetch_array ($result);
              $pid = $row['id'];
              $lastedit = $row['lastedit'];
            }
          mysql_free_result ($result);
        }
      
      $versionlist = array ();
      $result = mysql_query ("SELECT id, version, lastedit FROM ".db_maketablename ($table_pages_review)." WHERE guid LIKE '$guid' ORDER BY version DESC");
      if (mysql_num_rows ($result) > 0)
        {
          $i = 0;
          while ($row = mysql_fetch_array ($result))
            {
              if (empty ($pid))
                $pid = $row['id'];
              if (empty ($version))
                $version = $row['version'];
              if (empty ($lastedit))
                $lastedit = $row['lastedit'];
              $versionlist[$i] = $row['version'];
              $i++;
            }
        }
      mysql_free_result ($result);
      sort ($versionlist);
    }
?>
<h1>
  <?=$sitename?>
  <a href="<?=$protocol?>://<?=$domainname?>/" title="Go to website" rel="external"><img src="./images/link.gif" alt="<?=$sitename?>" class="externallink" /></a>
</h1>

<div id="sitetree">
  <h3><?=$domainname?></h3>
  <table cellpadding="0" cellspacing="0" style="width: 100%">
<?php
/* Print the site tree */
$guidlist = array ();
$result = mysql_query ("SELECT id, path, guid FROM ".db_maketablename ($table_pages_review)." WHERE path LIKE '[root]' ORDER BY path");
if (mysql_num_rows ($result) > 0)
  {
    $row = mysql_fetch_array ($result);
    print "<tr><td colspan=\"2\"><a href=\"./?p=pages&amp;guid={$row['guid']}\"><strong>/</strong> <span class=\"smalltext\">&rarr; Root element</span></a></td></tr>\n";
    $guidlist[0] = $row['guid'];
  }
mysql_free_result ($result);

$result = mysql_query ("SELECT id, path, guid FROM ".db_maketablename ($table_pages_review)." ORDER BY path");
if (mysql_num_rows ($result) > 0)
  {
    $i = 1;
    while ($row = mysql_fetch_array ($result))
      {
        if (!in_array ($row['guid'], $guidlist))
          {
            $path = "/".htmlentities ($row['path'], ENT_COMPAT, "UTF-8", false);
            print "<tr><td><a href=\"./?p=pages&amp;guid={$row['guid']}\"><strong>$path</strong></a></td>";
            print "<td class=\"alignright\"><a href=\"javascript:delpage('$path', {$row['id']});\" title=\"Delete '$path'\"><strong>&times;</strong></a></td></tr>\n";
          }
        $guidlist[$i] = $row['guid'];
        $i++;
      }
  }
mysql_free_result ($result);
?>
  </table>
  
  <div id="addnew1">
    <p>
      <input type="button" value="+" onclick="document.getElementById('addnew2').style.display='block';" class="button" />
      Add new page
    </p>
  </div>
  
  <div id="addnew2">
    <form action="../includes/addpage.php" method="post">
      <table cellpadding="0" cellspacing="0">
        <tr>
          <td><strong>Path:</strong></td>
          <td><input type="text" name="path" maxlength="255" value="/Type_path_here" class="textfield" /></td>
        </tr>
        <tr>
          <td><strong>Template:</strong>&nbsp;</td>
          <td>
            <select name="template">
<?php
/* Print the list of templates */
$result = mysql_query ("SELECT id, name FROM ".db_maketablename ($table_templates)." ORDER BY name");
if (mysql_num_rows ($result) > 0)
  {
    while ($row = mysql_fetch_array ($result))
      print "<option value=\"{$row['id']}\">".htmlentities ($row['name'], ENT_COMPAT, "UTF-8", false).".xsl</option>\n";
  }
mysql_free_result ($result);
?>
            </select>
          </td>
        </tr>
        <tr>
          <td colspan="2"><input type="submit" value="Add &raquo;" class="button" /></td>
        </tr>
      </table>
    </form>
  </div>

<?php
if (getsetting ($connection, "use_datasheets") == 1)
{
?>
  <div id="separator">&nbsp;</div>

  <h3>Datasheets</h3>
  <table cellpadding="0" cellspacing="0" style="width: 100%">
<?php
/* Print the list of datasheets */
$tbl_datasheets_def = db_maketablename ($table_datasheets_def);
$tbl_datasheets_rel = db_maketablename ($table_datasheets_rel);
$result = mysql_query ("SELECT $tbl_datasheets_def.id AS id, name FROM $tbl_datasheets_rel LEFT JOIN $tbl_datasheets_def ON $tbl_datasheets_rel.datasheet_id=$tbl_datasheets_def.id ORDER BY name");
if (mysql_num_rows ($result) > 0)
  {
    while ($row = mysql_fetch_array ($result))
      {
        $name = htmlentities ($row['name'], ENT_COMPAT, "UTF-8", false).".xml";
        print "<tr><td><a href=\"./?p=templates&amp;tid={$row['id']}\"><strong>$name</strong></a></td>\n";
      }
  }
else
  print "<tr><td><em>No active datasheets</em></td>\n";
mysql_free_result ($result);
?>
  </table>
<?php
} /* getsetting ($connection, "use_datasheets") == 1 */
?>

</div>

<div id="editor">
<?php
/* If no page is selected... */
if (empty ($guid))
{
?>
  <div id="info">
    <p>&larr; Click on an item in the site tree to edit it.</p>
  </div>
<?php
}
else
{
?>
    <form action="../includes/savepage.php" method="post">
      <div id="tabs">
        <span class="alignright">
          <strong>Version:</strong>
          <select onchange="window.location='./?p=site&guid=<?=$guid?>&ver='+this.options[this.selectedIndex].value+'&show='+document.getElementById ('show').value;">
<?php
foreach ($versionlist as $ver)
{
  $sel = $ver == $version ? " selected=\"selected\"" : "";
  print "<option value=\"$ver\"$sel>$ver</option>";
}
?>
          </select>
          <input type="submit" name="addversion" value="+" />
        </span>
        
        <ul>
          <li><a href="javascript:switchtabs ('tab1');">Page</a></li>
          <li><a href="javascript:switchtabs ('tab2');">Settings</a></li>
          <li><a href="javascript:switchtabs ('tab3');">Publish</a></li>
        </ul>
      </div>
    
      <div id="tab1">
<?php
  $tbl_pages = db_maketablename ($table_pages_review);
  $tbl_templates = db_maketablename ($table_templates);
  $result = mysql_query ("SELECT path, fields, template, xmlfeed, starttime, endtime FROM $tbl_pages LEFT JOIN $tbl_templates ON $tbl_templates.id=$tbl_pages.template WHERE $tbl_pages.id='$pid'");
  if (mysql_num_rows ($result) > 0)
    {
      $row = mysql_fetch_array ($result);
      
      /* Handle path */
      $path = $row['path'] == "[root]" ? "/" : "/{$row['path']}";
      $disabledpath = $row['path'] == "[root]" ? " disabled=\"disabled\"" : "";
      $templateid = $row['template'];
      
      /* Publishing options */
      if (!ini_get ('date.timezone'))
        date_default_timezone_set ("UTC");
      $startdate = $row['starttime'] == 0 ? "00/00/0000" : date ("m/d/Y", $row['starttime']);
      $starttime = $row['starttime'] == 0 ? "00:00" : date ("h:i", $row['starttime']);
      $startpm = date ("a", $row['starttime']) == "pm" ? 1 : 0;
      $enddate = $row['endtime'] == 0 ? "00/00/0000" : date ("m/d/Y", $row['endtime']);
      $endtime = $row['endtime'] == 0 ? "00:00" : date ("h:i", $row['endtime']);
      $endpm = date ("a", $row['endtime']) == "pm" ? 1 : 0;
      $noend = $row['endtime'] == 0 ? 1 : 0;
     
      /* Parse fields and xmlfeed */
      $out = xmlfeed_title ($row['xmlfeed']);
      $hash = md5 ($out);
      print "<label>Title</label><br /><input type=\"text\" name=\"title\" value=\"".htmlentities ($out, ENT_COMPAT, "UTF-8", false)."\" class=\"textfield\" onkeyup=\"needsave (this.value,'$hash');\" />\n";
      
      /* Prepare the XML parser and parse the data */
      $xmldata = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n".$row['fields'];     
      $xmlres = xml_parser_create ("utf-8");
      xml_parse_into_struct ($xmlres, $xmldata, $values);
      xml_parser_free ($xmlres);
      
      /* Walk through the tags */
      $num_html = xmlfeed_numhtmlfields ($row['fields']);
      $count_html = 1;
      $i = 0;
      while (!empty ($values[$i]))
        {
          if ($values[$i]['level'] == 2 && strcasecmp ($values[$i]['tag'], "field") == 0 && isset ($values[$i]['attributes']['NAME']) && isset ($values[$i]['attributes']['LABEL']) && isset ($values[$i]['attributes']['TYPE']))
            {
              $row['xmlfeed'] = stripslashes ($row['xmlfeed']);
              print "<label>{$values[$i]['attributes']['LABEL']}</label><br />";
              if ($values[$i]['attributes']['TYPE'] == "text")
                {
                  $out = xmlfeed_value ($row['xmlfeed'], $values[$i]['attributes']['NAME']);
                  $hash = md5 ($out);
                  print "<input type=\"text\" name=\"{$values[$i]['attributes']['NAME']}\" value=\"$out\" class=\"textfield\" onkeyup=\"needsave (this.value,'$hash');\" /><br />\n";
                }
              else if ($values[$i]['attributes']['TYPE'] == "largetext")
                {
                  $out = largetext_unformat (preg_replace ("/<br.*?>/", "\n", xmlfeed_value ($row['xmlfeed'], $values[$i]['attributes']['NAME'])));
                  $hash = md5 ($out);
                  print "<textarea id=\"largetext\" name=\"{$values[$i]['attributes']['NAME']}\" onkeyup=\"needsave (this.value,'$hash');\">$out</textarea><br />\n";
                }
              else if ($values[$i]['attributes']['TYPE'] == "html")
                {
                  $out = xmlfeed_value (stripslashes ($row['xmlfeed']), $values[$i]['attributes']['NAME']);
                  print "<textarea id=\"htmleditor$count_html\" name=\"{$values[$i]['attributes']['NAME']}\">$out</textarea><br />\n";
                  $count_html++;
                }
              else if ($values[$i]['attributes']['TYPE'] == "image")
                {
                  $out = xmlfeed_value ($row['xmlfeed'], $values[$i]['attributes']['NAME']);
                  $hash = md5 ($out);
                  print "<input type=\"text\" id=\"{$values[$i]['attributes']['NAME']}\" name=\"{$values[$i]['attributes']['NAME']}\" value=\"$out\" class=\"smalltextfield\" readonly=\"readonly\" />\n";
                  print "<input type=\"button\" value=\"Pick\" onclick=\"opendialog ('pickfile.php?field1={$values[$i]['attributes']['NAME']}', 770, 650); needsave (this.value, '');\" /><br/>\n";
                }
            }
          $i++;
        }
    }
  mysql_free_result ($result);
?>
      </div>
      
      <div id="tab2">
        <label>Path</label><br />
        <?php $hash = md5 ($path); ?>
        <input type="text" name="path" value="<?=htmlentities ($path, ENT_COMPAT, "UTF-8", false)?>"<?=$disabledpath?> class="textfield" onkeyup="needsave (this.value,'<?=$hash?>');" /><br />
        <label>Active template</label><br />
        <select name="template">
<?php
/* Print the list of templates */
$result = mysql_query ("SELECT id, name FROM ".db_maketablename ($table_templates)." ORDER BY name");
if (mysql_num_rows ($result) > 0)
  {
    while ($row = mysql_fetch_array ($result))
      {
        $selected = $row['id'] == $templateid ? " selected=\"selected\"" : "";
        print "<option value=\"{$row['id']}\"$selected>".htmlentities ($row['name'], ENT_COMPAT, "UTF-8", false).".xsl</option>\n";
      }
  }
mysql_free_result ($result);
?>
        </select>
      </div>
      
      <div id="tab3">
        <h3>Go live</h3>
        <label>Date (MM/DD/YYYY) and time (HH:MM)</label><br />
        <input type="text" name="startdate" maxlength="10" id="startdate" value="<?=$startdate ?>" class="date" onchange="needsave (this.value,'<?=md5 ($startdate) ?>');" />
        <input type="text" name="starttime" maxlength="5" value="<?=$starttime ?>" class="time" onkeyup="needsave (this.value,'<?=md5 ($starttime) ?>');" />
        <select name="startpm" onchange="needsave (this.value,'<?=md5 ($startpm) ?>');">
          <option value="0"<?=$startpm == 0 ? " selected=\"selected\"" : "" ?>>AM</option>
          <option value="1"<?=$startpm == 1 ? " selected=\"selected\"" : "" ?>>PM</option>
        </select>
        Go live now? <input type="checkbox" name="startnow" id="startnow" value="on" onclick="if (this.checked) document.getElementById ('endnow').checked = false;" onchange="needsave (this.value,'<?=md5 (1) ?>');" /><br />
        <input type="checkbox" name="noenddate" value="on"<?=!empty ($noend) ? " checked=\"checked\"" : "" ?> onclick="toogle_noend (this.checked);" onchange="needsave (this.value,'<?=md5 (1) ?>');" /> <label>No end date</label><br />&nbsp;

        <h3>Take down</h3>
        <label>Date (MM/DD/YYYY) and time (HH:MM)</label><br />
        <input type="text" name="enddate" id="enddate" maxlength="10" value="<?=$enddate ?>" class="date"<?=!empty ($noend) ? " disabled=\"disabled\"" : "" ?> onchange="needsave (this.value,'<?=md5 ($enddate) ?>');" />
        <input type="text" name="endtime" id="endtime" maxlength="5" value="<?=$endtime ?>" class="time"<?=!empty ($noend) ? " disabled=\"disabled\"" : "" ?> onkeyup="needsave (this.value,'<?=md5 ($endtime) ?>');" />
        <select name="endpm" id="endpm"<?=!empty ($noend) ? " disabled=\"disabled\"" : "" ?> onchange="needsave (this.value,'<?=md5 ($endpm) ?>');">
          <option value="0"<?=$endpm == 0 ? " selected=\"selected\"" : "" ?>>AM</option>
          <option value="1"<?=$endpm == 1 ? " selected=\"selected\"" : "" ?>>PM</option>
        </select>
        Take down now? <input type="checkbox" name="endnow" id="endnow" value="on"<?=!empty ($noend) ? " disabled=\"disabled\"" : "" ?> onclick="if (this.checked) document.getElementById ('startnow').checked = false;" onchange="needsave (this.value,'<?=md5 (1) ?>');" />
      </div>
      
      <p class="alignright operate">
        &nbsp;<br />
        <input type="hidden" name="pid" value="<?=$pid ?>" />
        <input type="hidden" name="guid" value="<?=$guid ?>" />
        <input type="hidden" name="pagever" value="<?=$version ?>" />
        <input type="hidden" id="show" name="show" value="<?=isset ($_GET['show']) ? $_GET['show'] : 1; ?>" />
        <input type="submit" id="btnsave" value="Save" class="button" />
        <input type="button" id="btnpreview" value="Preview" onclick="preview ('<?=$guid ?>', '<?=$version ?>');" class="button" />
      </p>
<?php
/* Show approve button */
$lastedit_live = 0;
$result = mysql_query ("SELECT lastedit FROM ".db_maketablename ($table_pages)." WHERE guid LIKE '$guid' AND version='$version'");
$num = mysql_num_rows ($result);
if ($num > 0)
{
  $row = mysql_fetch_array ($result);
  $lastedit_live = $row['lastedit'];
}
mysql_free_result ($result);

if ($lastedit_live < $lastedit)
{
?>
      <p class="alignleft operate">
        &nbsp;<br />
        <input type="submit" name="approve" value="Approve" class="button" />
<?php
if ($num > 0)
  print "<input type=\"submit\" name=\"revert\" value=\"Revert\" class=\"button\" />";
?>
     </p>
<?php
} /* $lastedit_live < $lastedit */
?>
    </form>
<?php
}
?>
</div>

<div class="clear"></div>

<script type="text/javascript">
  // <![CDATA[
    switchtabs ('<?=isset ($_GET['show']) ? "tab{$_GET['show']}" : "tab1"; ?>');
  // ]]>
</script>
<?php
}
?>
